package com.xmx.confu_work.useAdmin.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xmx.confu_work.useAdmin.entity.User;
import com.xmx.confu_work.useAdmin.mapper.UserMapper;
import com.xmx.confu_work.useAdmin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.omg.CORBA.TIMEOUT;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dinzhen
 * @since 2024-04-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(User user) {
        //根据用户名和密码查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        //新的不一样，结果不为空，密码要一样，则生成token，并将用户数据存入redis
//        wrapper.eq(User::getPassword,user.getPassword());
//        User select = userMapper.selectOne(wrapper);
        User select = this.baseMapper.selectOne(wrapper);
        //结果不为空就生成token，把用户信息存到redis里面
        if (select != null && passwordEncoder.matches(user.getPassword(),select.getPassword())){
            //暂时用UUID，等会用jwt
            String key = "user"+ UUID.randomUUID();

            //存入redis
            select.setPassword(null);
            redisTemplate.opsForValue().set(key,select,30,TimeUnit.MINUTES);
            //以上默认持续有效，但是密码等必须有时间限制,这里是30分钟

            //返回数据
            Map<String,Object> data = new HashMap<>();
            data.put("token",key);
            return data;
        }

       return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String token) {
        //根据token获取用户信息
        Object obj = redisTemplate.opsForValue().get(token);
        if (obj != null){
            //json字符串反序列化
            User loginUser = JSON.parseObject(JSON.toJSONString(obj),User.class);
            Map<String,Object> data = new HashMap<>();
            data.put("name",loginUser.getUsername());
            data.put("avator",loginUser.getAvatar());
            //角色
            List<String> roleList = this.userMapper.getRoleNameByUserId(loginUser.getId());
            data.put("roles", roleList);
            return data;
        }
        return null;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }
}
